import React, { useState, useRef } from 'react';
import { motion } from 'framer-motion';
import { Upload, Image as ImageIcon, Wand2, AlertCircle, CheckCircle } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { createTextToImageDesign, TextToImageRequest, getDesignStatus } from '../services/design';

interface TextToImageDesignProps {
  onDesignCreated: (imageUrl: string) => void;
  onCreditsUpdated: () => void;
}

const TextToImageDesign: React.FC<TextToImageDesignProps> = ({
  onDesignCreated,
  onCreditsUpdated
}) => {
  const { user } = useAuth();
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [prompt, setPrompt] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [currentPollInterval, setCurrentPollInterval] = useState<NodeJS.Timeout | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Validate file type
      if (!file.type.startsWith('image/')) {
        setError('Please select a valid image file');
        return;
      }

      // Validate file size (max 10MB)
      if (file.size > 10 * 1024 * 1024) {
        setError('Image size must be less than 10MB');
        return;
      }

      setSelectedImage(file);
      setError(null);

      // Create preview
      const reader = new FileReader();
      reader.onload = (e) => {
        setImagePreview(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
  };

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault();
    const file = event.dataTransfer.files[0];
    if (file) {
      // Validate file type
      if (!file.type.startsWith('image/')) {
        setError('Please select a valid image file');
        return;
      }

      // Validate file size (max 10MB)
      if (file.size > 10 * 1024 * 1024) {
        setError('Image size must be less than 10MB');
        return;
      }

      setSelectedImage(file);
      setError(null);

      // Create preview
      const reader = new FileReader();
      reader.onload = (e) => {
        setImagePreview(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleGenerate = async () => {
    if (!selectedImage || !prompt.trim()) {
      setError('Please select an image and enter a prompt');
      return;
    }

    if (!user) {
      setError('Please log in to generate designs');
      return;
    }

    setIsGenerating(true);
    setError(null);
    setSuccess(null);

    try {
      const request: TextToImageRequest = {
        image: selectedImage,
        customPrompt: prompt.trim(),
        userId: user.id.toString()
      };

      console.log('Creating text-to-image design with:', {
        customPrompt: prompt.trim(),
        userId: user.id.toString(),
        fileSize: selectedImage.size,
        fileType: selectedImage.type
      });

      const response = await createTextToImageDesign(request);
      
      console.log('Create text-to-image design response:', response);

      if (response.success && response.data.id) {
        // Task created successfully, now poll for completion
        const taskId = response.data.id;
        
        // Update credits immediately if provided
        if (response.data.creditsUsed && onCreditsUpdated) {
          onCreditsUpdated();
        }
        
        // Poll for task completion
        const pollInterval = setInterval(async () => {
          try {
            console.log('Polling status for text-to-image task:', taskId);
            const statusData = await getDesignStatus(taskId);
            console.log('Status response:', statusData);
            
            if (statusData.success) {
              if (statusData.data.status === 'completed' && statusData.data.generatedImageUrl) {
                console.log('Text-to-image task completed successfully');
                clearInterval(pollInterval);
                setCurrentPollInterval(null);
                setProcessedImage(statusData.data.generatedImageUrl);
                setIsGenerating(false);
                setSuccess('Design generated successfully!');
                
                // Notify parent components
                if (onDesignCreated) {
                  onDesignCreated(statusData.data.generatedImageUrl);
                }
              } else if (statusData.data.status === 'failed') {
                console.log('Text-to-image task failed:', statusData.data.errorMessage);
                clearInterval(pollInterval);
                setCurrentPollInterval(null);
                setIsGenerating(false);
                setError(statusData.data.errorMessage || 'Design generation failed');
              } else {
                console.log('Text-to-image task still in progress, status:', statusData.data.status);
              }
              // If status is still 'pending' or 'processing', continue polling
            } else {
              console.error('Status check failed:', statusData.message);
            }
          } catch (pollError) {
            const error = pollError as any;
            console.error('Error polling task status:', error);
            console.error('Poll error details:', {
              message: error.message,
              response: error.response?.data,
              status: error.response?.status
            });
            // Continue polling on error, don't break the loop
          }
        }, 3000); // Poll every 3 seconds
        
        // Store the interval reference
        setCurrentPollInterval(pollInterval);
      
        // Set a timeout to stop polling after 5 minutes
        setTimeout(() => {
          clearInterval(pollInterval);
          setCurrentPollInterval(null);
          if (isGenerating) {
            setIsGenerating(false);
            setError('Design generation timed out. Please try again.');
          }
        }, 300000); // 5 minutes timeout
        
      } else {
        throw new Error(response.message || 'Failed to create text-to-image design task');
      }
      
    } catch (error: any) {
      console.error('Error processing text-to-image:', error);
      console.error('Error details:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });
      
      let errorMessage = 'Failed to process image. Please try again.';
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      setError(errorMessage);
      setIsGenerating(false);
    }
  };

  const removeImage = () => {
    setSelectedImage(null);
    setImagePreview(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const [processedImage, setProcessedImage] = useState<string | null>(null);

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white rounded-2xl shadow-2xl border border-gray-100 p-6 md:p-8">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
          <h2 className="text-2xl font-bold text-gray-900 mb-4 sm:mb-0">Text to Image Design</h2>
          <button
            onClick={() => {
              setSelectedImage(null);
              setImagePreview(null);
              setProcessedImage(null);
              setPrompt('');
              setError(null);
              setSuccess(null);
              if (fileInputRef.current) {
                fileInputRef.current.value = '';
              }
            }}
            className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-blue-50 hover:border-blue-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-400 transition-all"
          >
            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Reset
          </button>
        </div>
        
        {/* Error Display */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <div className="flex items-center">
              <svg className="w-5 h-5 text-red-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
              <p className="text-red-800">{error}</p>
            </div>
          </div>
        )}

        {success && (
          <div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6">
            <div className="flex items-center">
              <CheckCircle className="w-5 h-5 text-green-400 mr-2" />
              <p className="text-green-800">{success}</p>
            </div>
          </div>
        )}
        
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Left Column - Upload and Settings */}
          <div className="space-y-6">
            {/* Image Upload Section */}
            <div>
              <label className="block text-lg font-medium text-gray-700 mb-2">
                Upload Your Room Photo
              </label>
              <div 
                className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-dashed rounded-2xl cursor-pointer bg-gradient-to-br from-blue-50 via-purple-50 to-white hover:shadow-[0_0_24px_4px_#a5b4fc] hover:border-blue-400 border-blue-200 transition-all duration-200"
                onClick={() => fileInputRef.current?.click()}
                onDragOver={handleDragOver}
                onDrop={handleDrop}
              >
                <div className="space-y-1 text-center">
                  {imagePreview ? (
                    <div className="relative">
                      <img
                        src={imagePreview}
                        alt="Uploaded room"
                        className="max-h-64 w-auto mx-auto rounded-xl shadow-lg"
                      />
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          removeImage();
                        }}
                        className="absolute top-2 right-2 bg-red-500 text-white p-2 rounded-full hover:bg-red-600 shadow-lg transition-colors"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      </button>
                    </div>
                  ) : (
                    <>
                      <svg
                        className="mx-auto h-16 w-16 text-blue-300 rounded-full bg-blue-50 p-2 shadow-md"
                        stroke="currentColor"
                        fill="none"
                        viewBox="0 0 48 48"
                      >
                        <path
                          d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                          strokeWidth={2}
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                      </svg>
                      <div className="flex text-sm text-gray-600 justify-center">
                        <span className="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 transition-all">Upload a file</span>
                        <p className="pl-1">or drag and drop</p>
                      </div>
                      <p className="text-xs text-gray-500">PNG, JPG, WebP up to 10MB</p>
                    </>
                  )}
                </div>
              </div>
              <input
                ref={fileInputRef}
                type="file"
                className="hidden"
                accept="image/*"
                onChange={handleImageSelect}
              />
            </div>
            
            {/* Prompt Section */}
            <div>
              <label className="block text-lg font-medium text-gray-700 mb-4">
                Design Prompt
              </label>
              
              <div className="space-y-4">
                <textarea
                  value={prompt}
                  onChange={(e) => setPrompt(e.target.value)}
                  placeholder="Describe your design vision... For example: 'Transform this room into a modern minimalist living space with neutral colors and clean lines'"
                  className="w-full h-32 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"
                  maxLength={500}
                />
                <div className="text-right text-sm text-gray-500">
                  {prompt.length}/500 characters
                </div>
              </div>

              {/* Example Prompts */}
              <div className="space-y-3 mt-4">
                <h3 className="text-sm font-medium text-gray-700">Example prompts:</h3>
                <div className="space-y-2">
                  {[
                    "Modern minimalist bedroom with warm lighting",
                    "Cozy living room with bohemian style and plants",
                    "Industrial kitchen with exposed brick and steel"
                  ].map((example, index) => (
                    <button
                      key={index}
                      onClick={() => setPrompt(example)}
                      className="block w-full text-left text-sm text-blue-600 hover:text-blue-800 hover:bg-blue-50 px-3 py-2 rounded transition-colors"
                    >
                      "{example}"
                    </button>
                  ))}
                </div>
              </div>
            </div>
            
            {/* Generate Button */}
            <div>
              {!isGenerating ? (
                <button
                  onClick={handleGenerate}
                  disabled={!selectedImage || !prompt.trim()}
                  className={`w-full py-3 px-4 rounded-xl text-white font-semibold text-lg shadow-lg transition-all duration-200
                    ${!selectedImage || !prompt.trim()
                      ? 'bg-gray-300 cursor-not-allowed'
                      : 'bg-gradient-to-r from-blue-500 to-purple-500 hover:scale-105 hover:shadow-[0_0_24px_6px_#a5b4fc]'}
                  `}
                >
                  Generate Design <span className="ml-2 text-sm opacity-80">(Cost: 1 credit)</span>
                </button>
              ) : (
                <div className="flex items-center justify-center py-2 bg-gray-100 rounded-lg">
                  <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  <span className="text-gray-700">Generating design, please wait...</span>
                </div>
              )}
            </div>
          </div>
          
          {/* Right Column - Generated Design */}
          <div className="bg-gradient-to-br from-blue-50 via-purple-50 to-white rounded-2xl shadow-xl border-2 border-blue-100 flex flex-col items-center justify-center min-h-[320px] p-6">
            {processedImage ? (
              <div className="w-full space-y-4">
                <img src={processedImage} alt="Generated design" className="w-full rounded-xl shadow-lg" />
                <button
                  onClick={async () => {
                    try {
                      const response = await fetch(processedImage);
                      const blob = await response.blob();
                      const url = window.URL.createObjectURL(blob);
                      const link = document.createElement('a');
                      link.href = url;
                      link.download = `text-to-image-design-${Date.now()}.jpg`;
                      document.body.appendChild(link);
                      link.click();
                      document.body.removeChild(link);
                      window.URL.revokeObjectURL(url);
                    } catch (error) {
                      console.error('下载失败:', error);
                    }
                  }}
                  className="w-full bg-gradient-to-r from-green-500 to-blue-500 text-white py-3 px-4 rounded-xl font-semibold hover:scale-105 hover:shadow-lg transition-all duration-200 flex items-center justify-center gap-2"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                  Download
                </button>
              </div>
            ) : (
              <div className="text-center text-gray-500">
                <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
                <p className="mt-2">Your generated design will appear here</p>
                <p className="text-sm">Upload an image and enter a prompt to start</p>
              </div>
            )}
          </div>
        </div>
        
        {/* Tips Section */}
        <div className="mt-8 bg-blue-50 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-blue-900 mb-3">Tips for better results:</h3>
          <ul className="space-y-2 text-blue-800">
            <li className="flex items-start gap-2">
              <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mt-2 flex-shrink-0" />
              Use high-quality, well-lit images for best results
            </li>
            <li className="flex items-start gap-2">
              <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mt-2 flex-shrink-0" />
              Be specific about colors, styles, and materials you want
            </li>
            <li className="flex items-start gap-2">
              <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mt-2 flex-shrink-0" />
              Mention the room type and desired atmosphere
            </li>
            <li className="flex items-start gap-2">
              <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mt-2 flex-shrink-0" />
              Each generation costs 10 credits
            </li>
          </ul>
        </div>
      </div>
    </motion.div>
  );
};

export default TextToImageDesign;